var createError = require('http-errors');
var express = require('express');
var path = require('path');
var cookieParser = require('cookie-parser');
var logger = require('morgan');
var session = require('express-session');

var homeRouter = require('./routes/home');
var usersRouter = require('./routes/users');
var categoryRouter = require('./routes/category');
var productRouter = require('./routes/product.js');
var detailRouter = require('./routes/detail.js');
var cartRouter = require("./routes/cart.js");
var siteRouter = require("./routes/site.js");
var orderRouter = require("./routes/order.js");
var profileRouter = require("./routes/profile.js");


var app = express();

// view engine setup
app.set('views', path.join(__dirname, 'views'));
app.set('view engine', 'ejs');


app.use("*",function(req,res,next){
    next();
});

app.use(logger('dev'));
app.use(express.json());
app.use(express.urlencoded({ extended: false }));
// app.use(cookieParser());

app.use(session({//配置session中间键
    // session的密钥
    secret: 'mi_demo',
    resave: true,
    // 只要客户端与express服务器有接触,不管有没有读写使用session，强制对客户端对应的session的过期时间进行刷新
    rolling: true,
    // 只要客户端与express服务器有接触,不管有没有读写使用session，强制为用户在express初始化一个session
    saveUninitialized: true,
    // session的最大过期时间
    cookie: { maxAge: 1000 * 60 *20 }
}));
app.use(express.static(path.join(__dirname, 'public')));

app.use('/', homeRouter);
app.use('/user', usersRouter);
app.use('/category',categoryRouter);
app.use("/product",productRouter);
app.use("/detail",detailRouter);
app.use("/cart",cartRouter);
app.use("/site",siteRouter);
app.use("/order",orderRouter);
app.use("/profile",profileRouter);


app.use((req,res,next) =>{
    req.myPromise
        ? req.myPromise
            .then(result => res.send({status: 200,data:result}))
            .catch(error => res.send({ status: 199, message: error.message, data: null }))
        : next();
});

// catch 404 and forward to error handler
app.use(function(req, res, next) {
  next(createError(404));
});

// error handler
app.use(function(err, req, res, next) {
  // set locals, only providing error in development
  res.locals.message = err.message;
  res.locals.error = req.app.get('env') === 'development' ? err : {};

  // render the error page
  res.status(err.status || 500);
  res.render('error');
});

module.exports = app;
